package edu.lingnan.blog.auth.service;

import edu.lingnan.blog.auth.form.LoginMessage;
import edu.lingnan.blog.common.core.constant.RabbitMQConstants;
import edu.lingnan.blog.common.core.utils.ServletUtils;
import edu.lingnan.blog.common.core.utils.ip.IpUtils;
import edu.lingnan.blog.common.core.utils.uuid.UUID;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author cql
 */
@Service
public class RabbitMQService {


    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 发送消息带上唯一表示，防止消息丢失
     *
     * @param flag
     * @param msg
     * @param account
     */
    public void sendLoginMessage(boolean flag, String msg, String account) {
        HttpServletRequest request = ServletUtils.getRequest();
        String ip = IpUtils.getIpAddr(request);
        String header = request.getHeader("User-Agent");
        LoginMessage loginMessage = new LoginMessage(account, msg, flag, ip, header, new Date());
        CorrelationData correlationId = new CorrelationData(UUID.fastUUID().toString());
        rabbitTemplate.convertAndSend(RabbitMQConstants.LOGIN_EXCHANGE, RabbitMQConstants.LOGIN_ROUTING_KEY, loginMessage, correlationId);
    }


}
